"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from PyQt4 import QtCore
from PyQt4 import QtGui
from msnp.gui import UIText, Resources, GUIHelper, MyStyle, MySignal
from msnp.model import SettingsModel, MediaModel, PTPModel
from msnp.persistence import XMLController, PersistenceController
from msnp.service.synch import LocalSynchController
from msnp import gui
from msnp.service.synch.timer import SynchChangesTimer

class SettingsWidget(QtGui.QDialog):
    """This class contains the settings widget which displays the current settings to the user and enables the user to change settings.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __synchPossible: A boolean value, True if the synchronization button should be enabled, False otherwise.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __titleWidget: A QTabWidget object containing the __iconLable, __titleLabel and __butHelp.
        __iconLabel: A QLabel object.
        __titleLabel: A QLabel object.
        __butHelp: A QPushButton object connected to the method __help().
        __tabWidget: A QTabWidget object containing the __tabGeneral, __tabMsnpDB, __tabMediaDB, __tabPlayerDB and __tabSynch.
        __tabGeneral: A TabGeneral object.
        __tabMsnpDB: A TabMsnpDB object.
        __tabMediaDB: A TabMediaDB object.
        __tabPlayerDB: A TabPlayerDB object.
        __tabSynch: A TabSynch object.
        __buttonWidget: A QWidget object containing the __butDiscard and __butHelp.
        __butDiscard: A QPushButton object connected to the method __discard().
        __butHelp: A QPushButton object connected to the method __help().
    """
    
    def __init__(self, synchPossible, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        #read settings
        self.__settings = XMLController.readAllSettings()
        self.__synchPossible = synchPossible
#        self.__groups = groups
        self.setWindowTitle(UIText.TITLE_SETTINGS)
        self.setWindowIcon(QtGui.QIcon(Resources.IMAGE_SETTINGS))
        self.setFixedSize(600, 450)
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
#        self.setModal(True)
        GUIHelper.centerWidget(self)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initTitleWidget()
        self.__initTabs()
        self.__initButtonWidget()
        self.__mainLayout.addWidget(self.__titleWidget)
        self.__mainLayout.addWidget(self.__tabWidget)
        self.__mainLayout.addWidget(self.__buttonWidget)
        
    def __initTitleWidget(self):
        """Initializes the QWidget object __titleWidget and adds its contained items."""
        self.__initLabels()
        self.__initHelpButton()
        self.__titleWidget = QtGui.QWidget()
        hLayout = QtGui.QHBoxLayout()
        hLayout.addWidget(self.__iconLabel)
        hLayout.addWidget(self.__titleLabel)
        hLayout.addWidget(self.__butHelp)
        self.__titleWidget.setLayout(hLayout)
        
    def __initLabels(self):
        """Initializes the QLabel objects __titleLabel and __iconLabel."""
        #titlelabel
        self.__titleLabel = QtGui.QLabel(UIText.LABEL_SETTINGS)
        self.__titleLabel.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.__titleLabel.setFont(MyStyle.getFont18Bold())
        self.__titleLabel.setTextFormat(QtCore.Qt.RichText)
        #big settings icon
        self.__iconLabel = QtGui.QLabel()
        self.__iconLabel.setPixmap(QtGui.QPixmap(Resources.IMAGE_SETTINGS_ICON_BIG))
        self.__iconLabel.setAlignment(QtCore.Qt.AlignLeft)
        
    def __initTabs(self):
        """Initializes the QTabWidget object __tabWidget and adds its contained items."""
        self.__tabWidget = QtGui.QTabWidget(self)
        self.__tabGeneral = TabGeneral(self.__settings, self.__synchPossible, self)
        self.__tabMsnpDB = TabMsnpDB(self.__settings, self)
        self.__tabMediaDB = TabMediaDB(self.__settings, self)
        self.__tabPlayerDB = TabPlayerDB(self.__settings, self)
        self.__tabSynch = TabSynch(self.__settings)
        self.__tabWidget.addTab(self.__tabGeneral, UIText.LABEL_GENERAL)
        self.__tabWidget.addTab(self.__tabMsnpDB, UIText.LABEL_MSNP_DB_SETTINS) 
        self.__tabWidget.addTab(self.__tabMediaDB, UIText.LABEL_MEDIA_DB_SETTINGS)
        self.__tabWidget.addTab(self.__tabPlayerDB, UIText.LABEL_PLAYER_DB_SETTINGS)
        self.__tabWidget.addTab(self.__tabSynch, UIText.LABEL_SYNCH)
        
    def __initButtonWidget(self):
        """Initializes the QWidget object __buttonWidget and adds its contained items."""
        buttonLayout = QtGui.QHBoxLayout()
        self.__initButtons()
        buttonLayout.addWidget(self.__butDiscard)
        buttonLayout.addWidget(self.__butSave)
        self.__buttonWidget = QtGui.QWidget()
        self.__buttonWidget.setLayout(buttonLayout)
        
    def __initButtons(self):
        """Initializes the QPushButton objects __butSave and __butDiscard."""
        #save
        self.__butSave = QtGui.QPushButton(UIText.BUT_SAVE, self)
        self.__butSave.setFocusPolicy(QtCore.Qt.NoFocus)
        self.__butSave.setIcon(QtGui.QIcon(Resources.IMAGE_BUT_SAVE)) 
        #discard
        self.__butDiscard = QtGui.QPushButton(UIText.BUT_DISCARD, self)
        self.__butDiscard.setFocusPolicy(QtCore.Qt.NoFocus)
        self.__butDiscard.setIcon(QtGui.QIcon(Resources.IMAGE_BUT_DISCARD))
        #register handler
        self.connect(self.__butSave, QtCore.SIGNAL('clicked()'), self.__save)
        self.connect(self.__butDiscard, QtCore.SIGNAL('clicked()'), self.__discard)
        
    def __initHelpButton(self):
        """Initializes the QPushButton object __butHelp."""
        self.__butHelp = QtGui.QPushButton("", self)
        self.__butHelp.setFocusPolicy(QtCore.Qt.NoFocus)
        self.__butHelp.setFixedWidth(40)
        self.__butHelp.setIcon(QtGui.QIcon(Resources.IMAGE_BUT_HELP))
        #register handler
        self.connect(self.__butHelp, QtCore.SIGNAL('clicked()'), self.__help)
        
    def saveContent(self):
        """Checks the database credentials the user entered into the various fields of this widget.
        If the given databases are accessible the settings are stored.
        If the player database settings changed it synchronizes the data from the player database to the media database.
        """
        self.__settings = XMLController.readAllSettings()
        username = self.__settings.getCurrentUserSettings().getUsername()
        synchTime = self.__settings.getCurrentUserSettings().getLastPlayerSynch()
        playerDBSettings = self.__tabPlayerDB.getDBSettings()
        dbAccessible = PersistenceController.testPlayerDBCredentials(playerDBSettings)
        if dbAccessible:
            msnpDBSettings = self.__tabMsnpDB.getDBSettings()
            dbAccessible = PersistenceController.testDBCredentials(msnpDBSettings.getHost(), msnpDBSettings.getUser(), msnpDBSettings.getPassword())
            if dbAccessible:
                mediaDBSettings = self.__tabMediaDB.getDBSettings()
                dbAccessible = PersistenceController.testDBCredentials(mediaDBSettings.getHost(), mediaDBSettings.getUser(), mediaDBSettings.getPassword())
                if dbAccessible:
                    dbAccessible = PersistenceController.initMediaDatabase(mediaDBSettings.getHost(), mediaDBSettings.getUser(), mediaDBSettings.getPassword(), mediaDBSettings.getSchema())
                    PersistenceController.initPlayerDatabase(playerDBSettings, mediaDBSettings.getSchema())
#                    oldGroupSynchSettingsList = self.__settings.getCurrentUserSettings().getGroupSettingsList()
                    oldMediaDBSettings = self.__settings.getCurrentUserSettings().getMediaDatabaseSettings()
                    oldPlayerDBSettings = self.__settings.getCurrentUserSettings().getPlayerDatabaseSettings()
                    newUserSettings = SettingsModel.UserSettings()
                    newUserSettings.setUsername(username)
                    newUserSettings.setLastPlayerSynch(synchTime)
                    newUserSettings.setPlayerDatabaseSettings(playerDBSettings)
                    newUserSettings.setMSNPDatabaseSettings(msnpDBSettings)
                    newUserSettings.setMediaDatabaseSettings(mediaDBSettings)
                    newUserSettings.setGroupSettingsList(self.__tabSynch.getGroupSettingsList())
                    self.__settings.setCurrentUserSettings(newUserSettings)
                    successful = XMLController.storeSettings(self.__settings)
                    if successful:
#                        self.__synchWithGroups(oldMediaDBSettings, oldGroupSynchSettingsList)    
                        self.__synchWithPlayer(oldPlayerDBSettings, oldMediaDBSettings)
                    return successful
                else:
                    QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_DB_ERROR_MEDIADB_NOT_ACCESSIBLE, UIText.BUT_OK)
            else:
                QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_DB_ERROR_PTPDB_NOT_ACCESSIBLE, UIText.BUT_OK)
        else:
            QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_DB_ERROR_PLAYERDB_NOT_ACCESSIBLE, UIText.BUT_OK)
        return False
    
    def __synchWithPlayer(self, oldPlayerDBSettings, oldMediaDBSettings):
        """If the player database settings changed it synchronizes the data from the player database to the media database."""
        newPlayerDBSettings = self.__settings.getCurrentUserSettings().getPlayerDatabaseSettings()
        playerDBchanged = oldPlayerDBSettings.getHost() != newPlayerDBSettings.getHost() or oldPlayerDBSettings.getUser() != newPlayerDBSettings.getUser() or oldPlayerDBSettings.getSchema() != newPlayerDBSettings.getSchema()
        newMediaDBSettings = self.__settings.getCurrentUserSettings().getMediaDatabaseSettings()
        mediaDBchanged = oldMediaDBSettings.getHost() != newMediaDBSettings.getHost() or oldMediaDBSettings.getUser() != newMediaDBSettings.getUser() or oldMediaDBSettings.getSchema() != newMediaDBSettings.getSchema()
        if playerDBchanged or mediaDBchanged:
            QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_IMPORT_PLAYER_DATA_NEW_DB, UIText.BUT_OK)
            self.importPlayerData()
    
    def importPlayerData(self):
        """Imports the data from the player database into the media database."""
        MySignal.emitSynchEnableSignal(False, False, PTPModel.ReturnType.SUCCESSFUL)
        LocalSynchController.importPlayerData()
        self.close()
    
    def __save(self):
        """This method is called by the QPushButton object __butSave. Stores the settings and, if no error occurred, closes the widget."""
        successful = self.saveContent()
        if successful:
            SynchChangesTimer.startSynchChangesTimer()
            self.close()
        else:
            QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_ERROR_STORE_SETTINGS, UIText.BUT_OK)
        
    def __discard(self):
        """This method is called by the QPushButton object __butDiscard. Closes the widget without saving."""
        self.close()
        
    def __help(self):
        """This method is called by the QPushButton object __butHelp. Depending on the active tab a help text appears."""
        index = self.__tabWidget.currentIndex()
        currentTabWidget = self.__tabWidget.widget(index)
        if isinstance(currentTabWidget, TabGeneral):
            title = UIText.LABEL_GENERAL
            helpText = UIText.MSG_HELP_SETTINGS_GENERAL 
        elif isinstance(currentTabWidget, TabMediaDB):
            title = UIText.LABEL_MEDIA_DB_SETTINGS
            helpText = UIText.MSG_HELP_SETTINGS_MEDIA_DB
        elif isinstance(currentTabWidget, TabMsnpDB):
            title = UIText.LABEL_MSNP_DB_SETTINS
            helpText = UIText.MSG_HELP_SETTINGS_MSNP_DB
        elif isinstance(currentTabWidget, TabPlayerDB):
            title = UIText.LABEL_PLAYER_DB_SETTINGS
            helpText = UIText.MSG_HELP_SETTINGS_PLAYER_DB
        elif isinstance(currentTabWidget, TabSynch):
            title = UIText.LABEL_SYNCH
            helpText = UIText.MSG_HELP_SETTINGS_SYNCH
        else:
            title = UIText.MSG_HELP
            helpText = UIText.MSG_HELP_SETTINGS_FALLBACK
        QtGui.QMessageBox.information(self, title, helpText, UIText.BUT_OK)
        
    def enableSynchronization(self, enable):
        """This method sets the synchronization button of the __tabGeneral to the value of the given parameter."""
        if self.__tabGeneral != None:
            self.__tabGeneral.enableSynchronization(enable)
            
    def closeEvent(self, event):
        """This method is called when the widget is closing."""
        gui.GUIController.closeSettingsWidget()
        event.accept()

class TabGeneral(QtGui.QWidget):
    """This class contains the general settings tab where general information are displayed and a button which enables the user to synchronize towards the media player.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __synchPossible: A boolean value, True if the synchronization button should be enabled, False otherwise.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __userDataWidget: A QWidget object containing the items __lblUsernameBold and __lblUsername.
        __lblUsernameBold: A QLabel object.
        __lblUsername: A QLabel object.
        __playerSynchWidget: A QWidget object.
        __lblLastPlayerSynchBold: A QLabel object.
        __lblLastPlayerSynch: A QLabel object.
        __butImport: A QPushButton object connected to the method __importPlayerData().
    """
    def __init__(self, settings, synchPossible, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__settings = settings
        self.__synchPossible = synchPossible
        self.__parent = parent
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initLabels()
        self.__initButton()
        self.__initUserDataWidget()
        self.__initPlayerSynchWidget()
        self.__mainLayout.addWidget(self.__userDataWidget)
        self.__mainLayout.addWidget(self.__playerSynchWidget)
        self.__mainLayout.addWidget(self.__butImport)
        
    def __initUserDataWidget(self):
        """Initializes the QWidget object __userDataWidget and adds its contained items."""
        self.__userDataWidget = QtGui.QWidget()
        hLayout = QtGui.QHBoxLayout()
        self.__userDataWidget.setLayout(hLayout)
        hLayout.addWidget(self.__lblUsernameBold)
        hLayout.addWidget(self.__lblUsername)
        
    def __initPlayerSynchWidget(self):
        """Initializes the QWidget object __playerSynchWidget and adds its contained items."""
        self.__playerSynchWidget = QtGui.QWidget()
        hLayout = QtGui.QHBoxLayout()
        self.__playerSynchWidget.setLayout(hLayout)
        hLayout.addWidget(self.__lblLastPlayerSynchBold)
        hLayout.addWidget(self.__lblLastPlayerSynch)
        
    def __initButton(self):
        """Initializes the QPushButton object __butImport."""
        self.__butImport = QtGui.QPushButton(UIText.BUT_IMPORT_PLAYER_DATA, self)
        self.__butImport.setFocusPolicy(QtCore.Qt.NoFocus)
        self.__butImport.setEnabled(self.__synchPossible)
        self.__butImport.setIcon(QtGui.QIcon(Resources.IMAGE_SYNCHRONIZE_ICON))
        #register handler
        self.connect(self.__butImport, QtCore.SIGNAL('clicked()'), self.__importPlayerData)
        
    def __initLabels(self):
        """Initializes the QLabel objects __lblUsernameBold, __lblUsername, __lblLastPlayerSynchBold and __lblLastPlayerSynch."""
        #username
        self.__lblUsernameBold = QtGui.QLabel(UIText.LABEL_USERNAME + ":")
        self.__lblUsernameBold.setFont(MyStyle.getFont13Bold())
        self.__lblUsername = QtGui.QLabel(self.__settings.getCurrentUserSettings().getUsername())
        #last player synch
        self.__lblLastPlayerSynchBold = QtGui.QLabel(UIText.LABEL_LAST_PLAYER_SYNCH + ":")
        self.__lblLastPlayerSynchBold.setFont(MyStyle.getFont13Bold())
        if self.__settings.getCurrentUserSettings().getLastPlayerSynch().getLastProcessedId() == -1:
            self.__lblLastPlayerSynch = QtGui.QLabel(UIText.LABEL_NO_SYNCH_YET)
        else:
            self.__lblLastPlayerSynch = QtGui.QLabel(self.__settings.getCurrentUserSettings().getLastPlayerSynch().getDate())
        
    def __importPlayerData(self):
        """This method is called by the QPushButton object __butImport. If the database credentials were entered correctly it imports the data from the player database to the media database."""
        successful = self.__parent.saveContent()
        if successful:
            self.__settings = XMLController.readAllSettings()
            playerDB = self.__settings.getCurrentUserSettings().getPlayerDatabaseSettings()
            mediaDB = self.__settings.getCurrentUserSettings().getMediaDatabaseSettings()
            if playerDB.isComplete() and mediaDB.isComplete():
                reply = QtGui.QMessageBox.question(self, UIText.MSG_ATTENTION, UIText.MSG_REALLY_IMPORT_PLAYER_DATA, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
                if reply == QtGui.QMessageBox.Yes:
                    self.__parent.importPlayerData()
            else:
                QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_COMPLETE_SYNCH_DB_SETTINGS, UIText.BUT_OK)
        else:
            QtGui.QMessageBox.information(self, UIText.MSG_ATTENTION, UIText.MSG_ERROR_STORE_SETTINGS, UIText.BUT_OK)
            
    def enableSynchronization(self, enable):
        """This method sets the QPushButton object __butImport to the value of the given parameter."""
        self.__synchPossible = enable
        self.__butImport.setEnabled(enable)
            
            
class TabPlayerDB(QtGui.QWidget):
    """This class contains the player database settings tab.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __msnpDBWidget: A QWidget object containing the items __lblDBHost, __lblDBSchema, __lblDBUser, __lblDBPassword, __txtDBHost, __txtDBSchema, __txtDBUser and __txtDBPassword.
        __lblDBHost: A QLabel object.
        __lblDBSchema: A QLabel object.
        __lblDBUser: A QLabel object.
        __lblDBPassword: A QLabel object.
        __txtDBHost: A QLineEdit object.
        __txtDBSchema: A QLineEdit object.
        __txtDBUser: A QLineEdit object.
        __txtDBPassword: A QLineEdit object.
    """
    def __init__(self, settings, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__settings = settings
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initLabels()
        self.__initLineEdits()
        self.__initDBWidget()
        self.__mainLayout.addWidget(self.__msnpDBWidget)
    
    def __initDBWidget(self):
        """Initializes the QWidget object __msnpDBWidget and adds its contained items."""
        #create gridLayout
        gridLayout = QtGui.QGridLayout()
        gridLayout.addWidget(self.__lblDBHost, 1, 0)
        gridLayout.addWidget(self.__lblDBSchema, 2, 0)
        gridLayout.addWidget(self.__lblDBUser, 3, 0)
        gridLayout.addWidget(self.__lblDBPassword, 4, 0)
        gridLayout.addWidget(self.__txtDBHost, 1, 1)
        gridLayout.addWidget(self.__txtDBSchema, 2, 1)
        gridLayout.addWidget(self.__txtDBUser, 3, 1)
        gridLayout.addWidget(self.__txtDBPassword, 4, 1)
        #widget for gridlayout
        gridWidget = QtGui.QWidget()
        gridWidget.setLayout(gridLayout)
        #add widgets to vlayout
        vLayout = QtGui.QVBoxLayout()
        vLayout.addWidget(gridWidget)
        #add vlayout to playerDBWidget
        self.__msnpDBWidget = QtGui.QWidget()
        self.__msnpDBWidget.setLayout(vLayout)
    
    def __initLabels(self):
        """Initializes the QLabel objects __lblDBHost, __lblDBUser, __lblDBSchema and __lblDBPassword."""
        self.__lblDBHost = QtGui.QLabel(UIText.LABEL_HOST + ":")
        self.__lblDBUser = QtGui.QLabel(UIText.LABEL_USER + ":")
        self.__lblDBSchema = QtGui.QLabel(UIText.LABEL_SCHEMA + ":")
        self.__lblDBPassword = QtGui.QLabel(UIText.LABEL_PASSWORD + ":")
        
    def __initLineEdits(self):
        """Initializes the QLineEdit objects __txtDBHost, __txtDBUser, __txtDBSchema and __txtDBPassword."""
        self.__txtDBHost = QtGui.QLineEdit()
        self.__txtDBUser = QtGui.QLineEdit()
        self.__txtDBSchema = QtGui.QLineEdit()
        self.__txtDBPassword = QtGui.QLineEdit()
        self.__txtDBPassword.setEchoMode (QtGui.QLineEdit.Password)
        playerDBSettings = self.__settings.getCurrentUserSettings().getPlayerDatabaseSettings()
        self.__txtDBHost.setText(playerDBSettings.getHost())
        self.__txtDBUser.setText(playerDBSettings.getUser())
        self.__txtDBSchema.setText(playerDBSettings.getSchema())
        self.__txtDBPassword.setText(playerDBSettings.getPassword())
        
    def getDBSettings(self):
        """Parses the data the user entered into the various QLineEdit objects, creates a DatabaseSettings object and returns it."""
        host = unicode(str(self.__txtDBHost.text()))
        user = unicode(str(self.__txtDBUser.text()))
        password = unicode(str(self.__txtDBPassword.text()))
        schema = unicode(str(self.__txtDBSchema.text()))
        return SettingsModel.DatabaseSettings(host, user, password, schema, MediaModel.Player.AMAROK().getName())
        
        
class TabMsnpDB(QtGui.QWidget):
    """This class contains the network database settings tab.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __playerDBWidget: A QWidget object containing the items __lblDBHost, __lblDBSchema, __lblDBUser, __lblDBPassword, __txtDBHost, __txtDBSchema, __txtDBUser and __txtDBPassword.
        __lblDBHost: A QLabel object.
        __lblDBSchema: A QLabel object.
        __lblDBUser: A QLabel object.
        __lblDBPassword: A QLabel object.
        __txtDBHost: A QLineEdit object.
        __txtDBSchema: A QLineEdit object.
        __txtDBUser: A QLineEdit object.
        __txtDBPassword: A QLineEdit object.
    """
    def __init__(self, settings, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__settings = settings
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initLabels()
        self.__initLineEdits()
        self.__initDBWidget()
        self.__mainLayout.addWidget(self.__playerDBWidget)
    
    def __initDBWidget(self):
        """Initializes the QWidget object __playerDBWidget and adds its contained items."""
        #create gridLayout
        gridLayout = QtGui.QGridLayout()
        gridLayout.addWidget(self.__lblDBHost, 1, 0)
        gridLayout.addWidget(self.__lblDBSchema, 2, 0)
        gridLayout.addWidget(self.__lblDBUser, 3, 0)
        gridLayout.addWidget(self.__lblDBPassword, 4, 0)
        gridLayout.addWidget(self.__txtDBHost, 1, 1)
        gridLayout.addWidget(self.__txtDBSchema, 2, 1)
        gridLayout.addWidget(self.__txtDBUser, 3, 1)
        gridLayout.addWidget(self.__txtDBPassword, 4, 1)
        #widget for gridlayout
        gridWidget = QtGui.QWidget()
        gridWidget.setLayout(gridLayout)
        #add widgets to vlayout
        vLayout = QtGui.QVBoxLayout()
        vLayout.addWidget(gridWidget)
        #add vlayout to playerDBWidget
        self.__playerDBWidget = QtGui.QWidget()
        self.__playerDBWidget.setLayout(vLayout)
    
    def __initLabels(self):
        """Initializes the QLabel objects __lblDBHost, __lblDBUser, __lblDBSchema and __lblDBPassword."""
        self.__lblDBHost = QtGui.QLabel(UIText.LABEL_HOST + ":")
        self.__lblDBUser = QtGui.QLabel(UIText.LABEL_USER + ":")
        self.__lblDBSchema = QtGui.QLabel(UIText.LABEL_SCHEMA + ":")
        self.__lblDBPassword = QtGui.QLabel(UIText.LABEL_PASSWORD + ":")
        
    def __initLineEdits(self):
        """Initializes the QLineEdit objects __txtDBHost, __txtDBUser, __txtDBSchema and __txtDBPassword."""
        self.__txtDBHost = QtGui.QLineEdit()
        self.__txtDBUser = QtGui.QLineEdit()
        self.__txtDBSchema = QtGui.QLineEdit()
        self.__txtDBPassword = QtGui.QLineEdit()
        self.__txtDBPassword.setEchoMode (QtGui.QLineEdit.Password)
        msnpDBSettings = self.__settings.getCurrentUserSettings().getMSNPDatabaseSettings()
        self.__txtDBHost.setText(msnpDBSettings.getHost())
        self.__txtDBUser.setText(msnpDBSettings.getUser())
        self.__txtDBSchema.setText(msnpDBSettings.getSchema())
        self.__txtDBPassword.setText(msnpDBSettings.getPassword())
        #currently not possible to change msnp database settings
        self.__txtDBHost.setEnabled(False)
        self.__txtDBUser.setEnabled(False)
        self.__txtDBSchema.setEnabled(False)
        self.__txtDBPassword.setEnabled(False)
        
    def getDBSettings(self):
        """Parses the data the user entered into the various QLineEdit objects, creates a DatabaseSettings object and returns it."""
        player = MediaModel.Player.AMAROK().getName()
        host = unicode(str(self.__txtDBHost.text()))
        user = unicode(str(self.__txtDBUser.text()))
        password = unicode(str(self.__txtDBPassword.text()))
        schema = unicode(str(self.__txtDBSchema.text()))
        return SettingsModel.DatabaseSettings(host, user, password, schema, player)
    
    
class TabMediaDB(QtGui.QWidget):
    """This class contains the media database settings tab.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __mediaDBWidget: A QWidget object containing the items __lblDBHost, __lblDBSchema, __lblDBUser, __lblDBPassword, __txtDBHost, __txtDBSchema, __txtDBUser and __txtDBPassword.
        __lblDBHost: A QLabel object.
        __lblDBSchema: A QLabel object.
        __lblDBUser: A QLabel object.
        __lblDBPassword: A QLabel object.
        __txtDBHost: A QLineEdit object.
        __txtDBSchema: A QLineEdit object.
        __txtDBUser: A QLineEdit object.
        __txtDBPassword: A QLineEdit object.
    """
    def __init__(self, settings, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__settings = settings
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initLabels()
        self.__initLineEdits()
        self.__initDBWidget()
        self.__mainLayout.addWidget(self.__mediaDBWidget)
    
    def __initDBWidget(self):
        """Initializes the QWidget object __mediaDBWidget and adds its contained items."""
        #create gridLayout
        gridLayout = QtGui.QGridLayout()
        gridLayout.addWidget(self.__lblDBHost, 1, 0)
        gridLayout.addWidget(self.__lblDBSchema, 2, 0)
        gridLayout.addWidget(self.__lblDBUser, 3, 0)
        gridLayout.addWidget(self.__lblDBPassword, 4, 0)
        gridLayout.addWidget(self.__txtDBHost, 1, 1)
        gridLayout.addWidget(self.__txtDBSchema, 2, 1)
        gridLayout.addWidget(self.__txtDBUser, 3, 1)
        gridLayout.addWidget(self.__txtDBPassword, 4, 1)
        #widget for gridlayout
        gridWidget = QtGui.QWidget()
        gridWidget.setLayout(gridLayout)
        #add widgets to vlayout
        vLayout = QtGui.QVBoxLayout()
        vLayout.addWidget(gridWidget)
        #add vlayout to playerDBWidget
        self.__mediaDBWidget = QtGui.QWidget()
        self.__mediaDBWidget.setLayout(vLayout)
    
    def __initLabels(self):
        """Initializes the QLabel objects __lblDBHost, __lblDBUser, __lblDBSchema and __lblDBPassword."""
        self.__lblDBHost = QtGui.QLabel(UIText.LABEL_HOST + ":")
        self.__lblDBUser = QtGui.QLabel(UIText.LABEL_USER + ":")
        self.__lblDBSchema = QtGui.QLabel(UIText.LABEL_SCHEMA + ":")
        self.__lblDBPassword = QtGui.QLabel(UIText.LABEL_PASSWORD + ":")
        
    def __initLineEdits(self):
        """Initializes the QLineEdit objects __txtDBHost, __txtDBUser, __txtDBSchema and __txtDBPassword."""
        self.__txtDBHost = QtGui.QLineEdit()
        self.__txtDBUser = QtGui.QLineEdit()
        self.__txtDBSchema = QtGui.QLineEdit()
        self.__txtDBPassword = QtGui.QLineEdit()
        self.__txtDBPassword.setEchoMode (QtGui.QLineEdit.Password)
        mediaDBSettings = self.__settings.getCurrentUserSettings().getMediaDatabaseSettings()
        self.__txtDBHost.setText(mediaDBSettings.getHost())
        self.__txtDBUser.setText(mediaDBSettings.getUser())
        self.__txtDBSchema.setText(mediaDBSettings.getSchema())
        self.__txtDBPassword.setText(mediaDBSettings.getPassword())
        
    def getDBSettings(self):
        """Parses the data the user entered into the various QLineEdit objects, creates a DatabaseSettings object and returns it."""
        player = MediaModel.Player.AMAROK().getName()
        host = unicode(str(self.__txtDBHost.text()))
        user = unicode(str(self.__txtDBUser.text()))
        password = unicode(str(self.__txtDBPassword.text()))
        schema = unicode(str(self.__txtDBSchema.text()))
        return SettingsModel.DatabaseSettings(host, user, password, schema, player)
    
    
class TabSynch(QtGui.QWidget):
    """This class contains the group settings tab, where the user can change group-based synchronization settings.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __settings: A Settings object containing the stores settings.
        __mainLayout: A QVBoxLayout object containing all items of the widget.
        __groupSynchWidget: A QWidget object containing the items __checkBoxesIn, __checkBoxesOut, __lblInSynch and __lblOutSynch.
        __checkBoxesIn: A list of GroupSettingsCheckBox objects.
        __checkBoxesOut: A list of GroupSettingsCheckBox objects.
        __lblInSynch: A QLabel object.
        __lblOutSynch: A QLabel object.
    """
    def __init__(self, settings, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
#        self.__groups = groups
        self.__settings = settings
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self):
        """Adds the items to the widget."""
        self.__initLabels()
        self.__initCheckBoxWidgets()
        self.__mainLayout.addWidget(self.__groupSynchWidget)
        
    def __initCheckBoxWidgets(self):
        """Initializes the QWidget object __groupSynchWidget and its contained items."""
        groupSettings = self.__settings.getCurrentUserSettings().getGroupSettingsList()
        #to access checkboxes afterwards
        self.__checkBoxesIn = []
        self.__checkBoxesOut = []
        #create gridLayout
        gridLayoutIn = QtGui.QGridLayout()
        gridLayoutOut = QtGui.QGridLayout()
        #decide column
        column = 0
        row = 1
        if groupSettings != None and len(groupSettings) > 0:
            for groupSetting in groupSettings:
    #            displayname = group.getDisplayname()
                groupname = groupSetting.getGroupname()
                ownername = groupSetting.getOwnername()
                isCheckedIn = groupSetting.isSynchIn()
                isCheckedOut = groupSetting.isSynchOut()
                checkBoxIn = GroupSettingsCheckBox(groupname, ownername, isCheckedIn)
                checkBoxOut = GroupSettingsCheckBox(groupname, ownername, isCheckedOut)
                gridLayoutIn.addWidget(checkBoxIn, row, column)
                gridLayoutOut.addWidget(checkBoxOut, row, column)
                self.__checkBoxesIn.append(checkBoxIn)
                self.__checkBoxesOut.append(checkBoxOut)
                column = (column + 1) % 2
                if column == 0:
                    row = row + 1
        else:
            lblNoGroupsIn = QtGui.QLabel(UIText.LABEL_NO_GROUP_FOR_SYNCH)
            lblNoGroupsIn.setFont(MyStyle.getFont8Cursive())
            lblNoGroupsOut = QtGui.QLabel(UIText.LABEL_NO_GROUP_FOR_SYNCH)
            lblNoGroupsOut.setFont(MyStyle.getFont8Cursive())
            gridLayoutIn.addWidget(lblNoGroupsIn)
            gridLayoutOut.addWidget(lblNoGroupsOut)
        #widgets for gridlayouts
        gridWidgetIn = QtGui.QWidget()
        gridWidgetIn.setLayout(gridLayoutIn)
        gridWidgetOut = QtGui.QWidget()
        gridWidgetOut.setLayout(gridLayoutOut)
        scrollAreaIn = QtGui.QScrollArea()
        scrollAreaIn.setWidget(gridWidgetIn)
        scrollAreaOut = QtGui.QScrollArea()
        scrollAreaOut.setWidget(gridWidgetOut)
        #add widgets to vlayout
        vLayout = QtGui.QVBoxLayout()
        vLayout.addWidget(self.__lblInSynch)
        vLayout.addWidget(scrollAreaIn)
        vLayout.addWidget(self.__lblOutSynch)
        vLayout.addWidget(scrollAreaOut)
        #add vlayout to playerDBWidget
        self.__groupSynchWidget = QtGui.QWidget()
        self.__groupSynchWidget.setLayout(vLayout)
        
    
    def __initLabels(self):
        """Initializes the QLabel objects __lblInSynch and __lblOutSynch."""
        self.__lblInSynch = QtGui.QLabel(UIText.LABEL_SYNCH_IN + ":")
        self.__lblInSynch.setFont(MyStyle.getFont13Bold())
        self.__lblOutSynch = QtGui.QLabel(UIText.LABEL_SYNCH_OUT + ":")
        self.__lblOutSynch.setFont(MyStyle.getFont13Bold())
        
    def getGroupSettingsList(self):
        """Checks the two lists __checkBoxesIn and __checkBoxesOut, creates a GroupSettings object and returns it."""
        settingsList = []
        for checkBoxIn in self.__checkBoxesIn:
            groupname = checkBoxIn.getGroupname()
            ownername = checkBoxIn.getOwnername()
            isSynchIn = False
            isSynchOut = False
            if checkBoxIn.isChecked():
                isSynchIn = True
            for checkBoxOut in self.__checkBoxesOut:
                if checkBoxOut.getGroupname() == groupname and checkBoxOut.getOwnername() == ownername:
                    isSynchOut = False
                    if checkBoxOut.isChecked():
                        isSynchOut = True
                    break
            gSettings = SettingsModel.GroupSettings(groupname, ownername, isSynchOut, isSynchIn)
            settingsList.append(gSettings)
        return settingsList
        
class GroupSettingsCheckBox(QtGui.QCheckBox):
    """This class contains the group settings check boxes. For each group the user is a member of two such check boxes are generated,
    one to change the ingoing synchronization settings and one to change the outgoing synchronization settings.
    
    Parameters:
        __groupname: A String containing the name of the group.
        __ownername: A String containing the name of the owner.
        __isChecked: A boolean value, True if the check box should be checked, False otherwise.
    """
    def __init__(self, groupname, ownername, isChecked):
        """The init-method."""
        QtGui.QCheckBox.__init__(self)
        self.__groupname = groupname
        self.__ownername = ownername
        self.__isChecked = isChecked
        self.__build()
        
    def __build(self):
        """Adds and initializes the items of the widget."""
        self.setText(self.__groupname + " (" + self.__ownername + ")")
        self.setFont(MyStyle.getFont8())
        self.setChecked(self.__isChecked)
    
    def getGroupname(self):
        """Returns the group name of the check box."""
        return self.__groupname
    
    def getOwnername(self):
        """Returns the owner name of the check box."""
        return self.__ownername
